package BiliBili;

import common.ListNode;

/**
 * @author zhangmin
 * @create 2022-09-20 18:30
 */
public class Main_0920_1 {
    public ListNode longestList (ListNode head) {
        if (head==null||head.next==null){
            return head;
        }
        //找到第一个奇数节点
        ListNode p1=head;
        while (p1!=null&&p1.val%2!=1){
            p1=p1.next;
        }
        ListNode jsHead=helper(p1);
        //找到第一个偶数节点
        ListNode p2=head;
        while (p2!=null&&p2.val%2==1){
            p2=p2.next;
        }
        ListNode osHead=helper(p2);
        //找到两个链表的长度
        int jscountLen = countLen(jsHead);
        int oscountLen=countLen(osHead);
        return jscountLen>=oscountLen?jsHead:osHead;
    }
    public ListNode helper(ListNode head){
        if (head==null||head.next==null){
            return head;
        }
        ListNode p1=head,p2=head.next;
        ListNode resHead=new ListNode(p1.val),p=resHead;
        while(p2!=null){
            long sum=p1.val+p2.val;
            if (sum%2==0){
                p2=p2.next;
            }else {
                p.next=new ListNode(p2.val);
                p=p.next;
                p1=p2;
                p2=p2.next;
            }
        }
        return resHead;
    }
    public int countLen(ListNode head){
        if (head==null) return 0;
        int count=1;
        while (head!=null){
            count++;
            head=head.next;
        }
        return count;
    }
    public static void main(String[] args) {
        ListNode head=new ListNode(2,new ListNode(5,new ListNode(3,new ListNode(4,new ListNode(1)))));
        Main_0920_1 obj=new Main_0920_1();
        obj.longestList(head);

    }
}
